//package com.coincalf.service.impl;
//
//import com.aliyuncs.DefaultAcsClient;
//import com.aliyuncs.IAcsClient;
//import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
//import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
//import com.aliyuncs.exceptions.ClientException;
//import com.aliyuncs.exceptions.ServerException;
//import com.aliyuncs.profile.IClientProfile;
//import com.baomidou.mybatisplus.mapper.EntityWrapper;
//import com.coincalf.api.SmsApi;
//import com.coincalf.api.aliyuncs.AliyunConfig;
//import com.coincalf.api.aliyuncs.MailConfig;
//import com.coincalf.dto.RandCode;
//import com.coincalf.dto.RandCodeVerifyDTO;
//import com.coincalf.entity.Config;
//import com.coincalf.entity.Sms;
//import com.coincalf.service.ConfigService;
//import com.coincalf.service.RandCodeService;
//import com.coincalf.service.SmsService;
//import com.google.common.base.Strings;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.RandomStringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.i18n.LocaleContextHolder;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.stereotype.Service;
//import org.thymeleaf.context.Context;
//import org.thymeleaf.spring5.SpringTemplateEngine;
//
//import java.util.HashMap;
//import java.util.Map;
//import java.util.Optional;
//import java.util.concurrent.TimeUnit;
//
///**
// * @author qiang
// */
//@Service
//@Slf4j
//public class RandCodeServiceImpl implements RandCodeService {
//
//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;
//    @Autowired
//    private ConfigService configService;
//    @Autowired
//    private SmsService smsService;
//    @Autowired
//    private AliyunConfig aliyunConfig;
//    @Autowired
//    private MailConfig mailConfig;
//    @Autowired
//    private SpringTemplateEngine springTemplateEngine;
//
//    @Override
//    public void sendTo(RandCode randCode) {
//        String code = RandomStringUtils.randomNumeric(6);
//
//        EntityWrapper<Config> ew = new EntityWrapper<>();
//        ew.eq("type", "SMS");
//        ew.eq("code", randCode.getTemplateCode());
//        Config config = configService.selectOne(ew);
//        if (Optional.ofNullable(config).isPresent()) {
//            String content = config.getValue();
//            EntityWrapper<Config> signEntityWrapper = new EntityWrapper<>();
//            signEntityWrapper.eq("type", "SMS");
//            signEntityWrapper.eq("code", "SIGN");
//            Config signConfig = configService.selectOne(signEntityWrapper);
//            if (Optional.ofNullable(signConfig).isPresent()) {
//                content = content.replaceAll("\\$\\{".concat("sign").concat("\\}"), signConfig.getValue());
//            }
//            content = content.replaceAll("\\$\\{".concat("code").concat("\\}"), code);
//
//
//            if (!Strings.isNullOrEmpty(randCode.getPhone())) {
//                String key = String.format("CAPTCHA:%s:%s", randCode.getTemplateCode(), randCode.getCountryCode() + randCode.getPhone());
//
//                stringRedisTemplate.opsForValue().set(key, code);
//                stringRedisTemplate.expire(key, 30L, TimeUnit.MINUTES);
//
//                Sms sms = new Sms()
//                        .setTemplateCode(randCode.getTemplateCode())
//                        .setMobile(randCode.getPhone())
//                        .setStatus(1);
//                sms.setContent(content);
//                String result = SmsApi.sendTo(sms);
//                sms.setRemark(result);
//                smsService.insert(sms);
//                if (log.isDebugEnabled()) {
//                    log.debug(randCode.toString() + "[" + code + "]");
//                }
//            } else if (!Strings.isNullOrEmpty(randCode.getEmail())) {
//                String key = String.format("CAPTCHA:%s:%s", randCode.getTemplateCode(), randCode.getEmail());
//
//                stringRedisTemplate.opsForValue().set(key, code);
//                stringRedisTemplate.expire(key, 30L, TimeUnit.MINUTES);
//                // 如果是除杭州region外的其它region（如新加坡、澳洲Region），需要将下面的"cn-hangzhou"替换为"ap-southeast-1"、或"ap-southeast-2"。
//                IClientProfile profile = aliyunConfig.getProfile();
//                // 如果是除杭州region外的其它region（如新加坡region）， 需要做如下处理
//                //try {
//                //DefaultProfile.addEndpoint("dm.ap-southeast-1.aliyuncs.com", "ap-southeast-1", "Dm",  "dm.ap-southeast-1.aliyuncs.com");
//                //} catch (ClientException e) {
//                //e.printStackTrace();
//                //}
//                IAcsClient client = new DefaultAcsClient(profile);
//                SingleSendMailRequest request = new SingleSendMailRequest();
//                Sms sms = new Sms()
//                        .setTemplateCode(randCode.getTemplateCode())
//                        .setMobile(randCode.getEmail())
//                        .setStatus(1);
//                sms.setContent(content);
//                try {
//                    //request.setVersion("2017-06-22");// 如果是除杭州region外的其它region（如新加坡region）,必须指定为2017-06-22
//                    Map<String, Object> params = new HashMap<>();
//                    params.put("sign", signConfig.getValue());
//                    params.put("content", content);
//                    Context context = new Context(LocaleContextHolder.getLocale());
//                    context.setVariables(params);
//                    String htmlBody = springTemplateEngine.process("mail", context);
//                    request.setAccountName(mailConfig.getAccount());
//                    request.setFromAlias(signConfig.getValue());
//                    request.setAddressType(1);
//                    request.setReplyToAddress(true);
//                    request.setToAddress(randCode.getEmail());
//                    request.setSubject(config.getName());
//                    request.setHtmlBody(htmlBody);
//                    SingleSendMailResponse httpResponse = client.getAcsResponse(request);
//                    System.out.println(httpResponse.getRequestId());
//                    sms.setRemark(httpResponse.getRequestId());
//                } catch (ServerException e) {
//                    e.printStackTrace();
//                    sms.setRemark(e.getMessage());
//                } catch (ClientException e) {
//                    e.printStackTrace();
//                    sms.setRemark(e.getMessage());
//                } finally {
//                    smsService.insert(sms);
//                }
//            }
//        } else {
//            throw new RuntimeException("短信模板不存在！");
//        }
//    }
//
//    @Override
//    public boolean verify(RandCodeVerifyDTO randCodeVerifyDTO) {
//        String account = randCodeVerifyDTO.getEmail();
//        if (!Strings.isNullOrEmpty(randCodeVerifyDTO.getPhone())) {
//            account = randCodeVerifyDTO.getCountryCode() + randCodeVerifyDTO.getPhone();
//        }
//        String key = String.format("CAPTCHA:%s:%s", randCodeVerifyDTO.getTemplateCode(), account);
//        String value = stringRedisTemplate.opsForValue().get(key);
//        if (!Strings.isNullOrEmpty(account) && !Strings.isNullOrEmpty(value) && value.equals(randCodeVerifyDTO.getCode())) {
//            stringRedisTemplate.delete(key);
//            return true;
//        } else {
//            return false;
//        }
//    }
//
//}
